package com.ruoyi.config;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;


@Component
public class WeXinConfig {

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.secret}")
    private String secret;
    public Object getSessionId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String res = HttpUtil.get(replaceUrl);
        System.out.println("发送链接后获得的数据{}"+res);
        return res;
    }

    public Object getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret);
        String res = HttpUtil.get(replaceUrl);
        System.out.println("发送链接后获得的数据{}"+res);
        return res;
    }

    public String desEncrypt(String data, String key, String iv) throws Exception {
        byte[] encData =Base64.decode(data);
        byte[] ivs = Base64.decode(iv);
        byte[] keys = Base64.decode(key);
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivs);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(keys, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return new String(cipher.doFinal(encData), "UTF-8");
    }

}
